<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>无标题文档</title>
    <link href="../../css/style.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="../../js/jquery.js"></script>

    <script type="text/javascript" src="../../js/axios.js"></script>
    <script type="text/javascript" src="../../js/api.js"></script>

</head>

<body>
<div class="place"><span>位置：</span>
    <ul class="placeul">
        <li>采购管理</li>
        <li>采购单管理</li>
        <li>添加</li>
    </ul>
</div>
<div class="formbody">
    <div class="formtitle"><span>采购单信息</span></div>
    <form id="purchase">
        <ul class="forminfo">
            <li>
                <label>采购单编号</label>
                <input name="purchaseId" id="purchaseId" type="text" value="CG202211220001" readonly="readonly"
                       class="roinput"/>
                <i>自动生成不能编辑</i>
            </li>
            <li>
                <label>采购时间</label>
                <input name="purchaseTime" id="purchaseTime" type="text" value="2022-11-22 16:45:10" readonly="readonly"
                       class="roinput"/>
                <i>不能编辑</i>
            </li>
            <li>
                <label>创建人</label>
                <input id="uid" name="creatId" type="hidden" value="2" readonly="readonly" class="roinput"/>
                <input id="username" type="text" value="陌" readonly="readonly" class="roinput"/>
                <i>不能编辑</i>
            </li>
            <li>
                <label>审核状态</label>
                <input type="text" value="未审核" readonly="readonly" class="roinput"/>
                <input name="checkStatus" type="hidden" value="1"/>
                <i>初始状态，不能编辑</i>
            </li>
            <li>
                <label>总金额</label>
                <input name="totalMoney" id="money" type="text" readonly="readonly" class="roinput"/>
                <i>自动运算，不能编辑</i>
            </li>
            <li>
                <input type="button" id="addbutton" value="新增" class="smallbtn"/>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <input type="button" id="delbutton" value="删除" class="smallbtn"/>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <input type="button" id="submitbutton" value="保存" class="smallbtn"/>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <input type="button" value="返回" class="smallbtn" onclick="window.location.href='purchaseList.html'"/>
            </li>
        </ul>
    </form>
    <table class="tablelist">
        <thead>
        <tr>
            <th><input type="checkbox" id="checkAll">全选
            </th>
            <th>序号</th>
            <th>品牌</th>
            <th>类型</th>
            <th>型号</th>
            <th>厂商</th>
            <th>数量</th>
            <th>单位</th>
            <th>单价</th>
            <th>金额</th>
        </tr>
        </thead>
        <tbody id="tablebody">
        <!--  <tr>
              <td>1</td>
              <td>
                  <select >
                      <option>请选择</option>
                      <option>联想</option>
                      <option>海尔</option>
                      <option>小米</option>
                  </select>
              </td>
              <td>
                  <select>
                      <option>请选择</option>
                      <option>笔记本电脑</option>
                      <option>台式电脑</option>
                      <option>手机</option>
                  </select>
              </td>
              <td>
                  <select>
                      <option>请选择</option>
                      <option>X260</option>
                      <option>E470</option>
                      <option>T470</option>
                  </select>
              </td>
              <td>
                  <select>
                      <option>请选择</option>
                      <option>北京联想科技股份有限公司</option>
                      <option>北京京东商贸股份有限公司</option>
                  </select>
              </td>
              <td><input type="text"/></td>
              <td>台</td>
              <td><input type="text"/></td>
              <td><input type="text"/></td>
          </tr>-->
        </tbody>
    </table>
</div>
<script type="text/javascript" language="JavaScript">

    let brand = []; // 存放品牌
    let autoId = 1; //用于生成Id
    let productList = []; //用于存放商品信息
    let sum = 0;//总金额
    $('.tablelist tbody tr:odd').addClass('odd');
    $(function () {
        //加载品牌数据--将其存在一个全局变量里
        axiosJson('get', '/purchase/brand', null, null).then((res) => {
            brand = res.data.resultData;
            writeTable()
        })
        //采购单编号
        let date = new Date();
        let now = date.toLocaleDateString().replaceAll('/', '')//2021/11/22-->20211122
        let pid = 'CG' + now + (Math.round((Math.random() + 1) * 1000))
        console.log(pid)
        $('#purchaseId').val(pid)
        //采购时间
        let nowTime = date.toLocaleString().replaceAll('/', '-') //2022/11/22 20:22:34-->2022-11-22  20:22:34
        $('#purchaseTime').val(nowTime)
        $("#uid").val(localStorage.getItem("uId"))
        $("#username").val(localStorage.getItem("username"))
    })


    //通过brandId 查询类型
    function loadType(brandId, tid) {
        axiosJson('get', '/purchase/type', null, {brandId: brandId}).then((res) => {
            let type = res.data.resultData;
            let typeName = '<option value="0">--请选择--</option>'
            for (let i = 0; i < type.length; i++) {
                // console.log(type[i].typeName)
                typeName += '<option value="' + type[i].typeId + '">' + type[i].typeName + '</option>'
            }
            //填充到下拉框
            $('#' + tid).html(typeName)
        })
    }

    //通过typeId 查询商品信息(型号、厂商id、单价)
    function loadProduct(typeId, pid) {
        axiosJson('get', '/purchase/product', null, {typeId: typeId}).then((res) => {
            productList[pid.split("-")[0]] = res.data.resultData; //存进全局变量
            let pMName = '<option>--请选择--</option>'
            let product = res.data.resultData;
            for (let pm in product) {
                pMName += '<option >' + product[pm].productModel + '</option>'
            }
            //填充到下拉框
            $('#' + pid).html(pMName)
        })
    }

    //通过typeId、productModel 查询 厂商
    function loadFirm(tid, model, fid) {
        axiosJson('get', '/purchase/firm', null, {typeId: tid, productModel: model}).then((res) => {
            let firmName = '<option value="0">--请选择--</option>'
            let firm = res.data.resultData;
            for (let fm in firm) {
                firmName += '<option value="' + firm[fm].firmId + '">' + firm[fm].firmName + '</option>'
            }
            //填充到对应的字段
            $('#' + fid).html(firmName)
        })
    }

    //拼写表格数据
    function writeStr(autoId) {
        //品牌下拉框填充数据
        let brandName = ''
        for (let i = 0; i < brand.length; i++) {
            brandName += '<option value="' + brand[i].brandId + '">' + brand[i].brandName + '</option>'
        }
        let str =
            '<tr name="details" id="' + autoId + '" style="height: 30px">\n' +
            '            <td><input name="check" type="checkbox"></td>' +
            '            <td id="xh">1</td>\n' +
            '            <td>\n' +
            '                <select name="brandId" id="' + autoId + '-1">\n' +
            '                    <option value="0">--请选择--</option>\n' + brandName +
            '                </select>\n' +
            '            </td>\n' +
            '            <td>\n' +
            '                <select name="typeId" id="' + autoId + '-2">\n' +
            '                    <option value="0">--请选择--</option>\n' +
            '                </select>\n' +
            '            </td>\n' +
            '            <td>\n' +
            '                <select name="productModel" id="' + autoId + '-3">\n' +
            '                    <option value="0">--请选择--</option>\n' +
            '                </select>\n' +
            '            </td>\n' +
            '            <td>\n' +
            '                <select name="firmId" id="' + autoId + '-4">\n' +
            '                    <option value="0">--请选择--</option>\n' +
            '                </select>\n' +
            '            </td>\n' +
            '            <td><input name="count" id="' + autoId + '-5"  value="" type="number" min="0"/></td>\n' +
            '            <td><input name="productUnit" id="' + autoId + '-6" type="text"/></td>\n' +
            '            <td><input name="purchasePrice" id="' + autoId + '-7" type="text"/></td>\n' +
            '            <td><input name="totalMoney" id="' + autoId + '-8" class="price" type="text"/></td>\n' +
            '            <td><input name="productId" id="' + autoId + '-9"  value="" type="hidden"/></td>\n' +
            '        </tr>+'
        return str;
    }

    //当改变前一个input标签时，后面的input 标签会清空
    function cleanInput(autoId) {
        $('#' + autoId + '-5').val('')
        $('#' + autoId + '-6').val('')
        $('#' + autoId + '-7').val('')
        $('#' + autoId + '-8').val('')
        $('#' + autoId + '-9').val('')
    }

    //表格里的下拉框操作
    function operation(autoId) {
        //品牌框发生改变后、类型下拉框就要出现对应的类型
        $('#' + autoId + '-1').change(function () {
            let bid = $('#' + autoId + '-1').val()
            loadType(bid, autoId + '-2')
            $('#' + autoId + '-2').html('<option>--请选择--</option>')
            $('#' + autoId + '-3').html('<option>--请选择--</option>')
            $('#' + autoId + '-4').html('<option>--请选择--</option>')
            cleanInput(autoId);
        })

        //类型框，发生改变后，型号下拉框就要发生改变
        $('#' + autoId + '-2').change(function () {
            let tid = $('#' + autoId + '-2').val()
            loadProduct(tid, autoId + '-3')
            $('#' + autoId + '-3').html('<option>--请选择--</option>')
            $('#' + autoId + '-4').html('<option>--请选择--</option>')
            cleanInput(autoId);
        })

        //型号框确定后、由类型、型号可以缩小厂商
        $('#' + autoId + '-3').change(function () {
            let tid = $('#' + autoId + '-2').val()
            let model = $('#' + autoId + '-3').val()
            loadFirm(tid, model, autoId + '-4')
            $('#' + autoId + '-4').html('<option>--请选择--</option>')
            cleanInput(autoId);
        })

        //品牌、类型、型号、厂商确定后，就能确定商品id;去全局变量productList匹配相同的信息
        $('#' + autoId + '-4').change(function () {
            cleanInput(autoId);
            let fid = $('#' + autoId + '-4').val();
            for (let pl in productList[autoId]) {
                if (productList[autoId][pl].firmId == fid) {
                    // console.log(productList[pl].firmId)

                    $('#' + autoId + '-5').val(1)
                    $('#' + autoId + '-6').val(productList[autoId][pl].productUnit)
                    $('#' + autoId + '-7').val(productList[autoId][pl].productPrice)
                    $('#' + autoId + '-8').val(productList[autoId][pl].productPrice)
                    $('#' + autoId + '-9').val(productList[autoId][pl].productId)
                    totalMoney()
                }
            }
        })

        //当数量发生改变时，计算出总金额
        $('#' + autoId + '-5')[0].oninput = function () {
            let price = $('#' + autoId + '-7').val();
            let number = $('#' + autoId + '-5').val();
            let money = price * number;
            $('#' + autoId + '-8').val(money)
            totalMoney()
        }
    }

    //计算采购单的总金额
    function totalMoney() {
        let price = $('.price');
        sum = 0;
        for (let i = 0; i < price.length; i++) {
            sum += Number(price[i].value);
        }
        $('#money').val(sum)
    }

    //写数据
    function writeTable() {
        //拼写表格数据
        let s = writeStr(autoId);

        $('#tablebody').html(s)

        operation(autoId);
        selectAll();
        //新增一行商品
        $('#addbutton').click(() => {
            autoId++;//id生成自增
            $('#tablebody').append(writeStr(autoId))

            let xh = document.querySelectorAll("#xh");
            for (let i = 0; i < xh.length; i++) {
                xh[i].innerHTML = (i + 1)
            }

            operation(autoId);
            selectAll();
        })

        //删除选中行商品信息
        $('#delbutton').click(() => {
            //遍历所有 name=check 的复选框
            $("[name='check']").each(function () {
                //若被选中，则删除
                if ($(this).is(":checked")) {
                    $(this).parent().parent().remove()
                    totalMoney()
                }
            })
            let xh = document.querySelectorAll("#xh");
            for (let i = 0; i < xh.length; i++) {
                xh[i].innerHTML = (i + 1)
            }
        })

    }

    //保存 并返回到管理列表视图(退出添加页面)
    $('#submitbutton').click(() => {
        //获取行数
        let tr = $("[name='details'] ")
        let arr = [];
        //获取表格里的采购单信息
        for (let i = 0; i < tr.length; i++) {
            let obj = {};
            let id = $(tr[i]).attr("id");
            for (let j = 5; j <= 9; j++) {
                let $td = $(`#${id}-${j}`);
                obj[$td.attr("name")] = $td.val();
            }
            arr.push(obj)
        }
        let conn = $('#purchase').serializeArray();
        if (verification()) {
            axiosBody('/purchase/addPurchase', conn, arr).then((res) => {
                alert(res.data.msg)
                window.location.href = 'purchaseList.html';
            })
        } else {
            alert('请完善需采购的商品信息！')
        }
    })

    //商品信息(表格)非空验证、因为每行是由前往后填写的所以只需判断最后一个即厂商非空就好了
    function verification() {
        let tr = $("[name='details'] ")
        let flag = true;
        if (tr.length==0){
            flag=false
            alert("请添加商品信息")
        }else {
            for (let i = 0; i < tr.length; i++) {
                let fid = $(tr[i]).find("[name='firmId']").val();
                let count = $(tr[i]).find("[name='count']").val();
                if (fid == 0||count==0) {
                    flag = false;
                }
            }
        }

        return flag;
    }
</script>
</body>

</html>
